import AppointTaskModel from "../model/appointTask";
import dayjs from "dayjs";
import log from "../utils/log";
import PalaceHelper from "../middleware/palaceHelper";
import { getCalendartickt, getCanBuyDays } from "../thirdServices/palaceApi";

const getTicketDate = async () => {
  const res = await getCanBuyDays();
  if (res.data.code === 200) {
    const canJson = JSON.parse(res.data.data);
    const date = new Date(canJson.time);
    const endDate = new Date(canJson.time);
    endDate.setDate(date.getDate() + canJson.days);
    const params = {
      parkId: 11324,
      year: date.getFullYear(),
      // month: monthStr,
      merchantId: 2655,
      merchantInfoId: 2655
    };
    if (date.getMonth() === endDate.getMonth()) {
      const month = date.getMonth() + 1;
      const monthStr = month < 10 ? `0${month}` : `${month}`;
      try {
        const calendarRes = await getCalendartickt({ ...params,  month: monthStr });
        if (calendarRes.data.status === 200) {
          const list = calendarRes.data.data;
          return list.filter(item => dayjs(item.occDate) > dayjs(date) && dayjs(item.occDate) < dayjs(endDate));
        }  
      } catch (error) {
        console.log(error.response.data);
      }
      
    } else {
      try {
        const month = date.getMonth() + 1;
        const monthStr = month < 10 ? `0${month}` : `${month}`;
        const p1 = getCalendartickt({ ...params,  month: monthStr });

        const month2 = date.getMonth() + 2;
        const monthStr2 = month < 10 ? `0${month2}` : `${month2}`;
        const p2 = getCalendartickt({ ...params,  month: monthStr2 });

        const calendarRes = await Promise.all([p1, p2]);
        let list: any[] = [];
        if (calendarRes[0].data.status === 200) {
          list = list.concat(calendarRes[0].data.data);
        }

        if (calendarRes[1].data.status === 200) {
          list = list.concat(calendarRes[1].data.data);
        }
        return list.filter(item => dayjs(item.occDate) > dayjs(date) && dayjs(item.occDate) < dayjs(endDate));
      } catch (error) {
        console.log(error);
      }
    }
  }

  return [];
};

class PalaceTask {
  appointList: string[] = [];
  async init() {
    let modelList: any[] = [];
    try {
      modelList = await AppointTaskModel.getAppointList(1);
    } catch (error) {
      console.log(error)
    }
    this.appointList = modelList.map(model => {
      const date = model.getDataValue('appointDate');
      const hallScheduleId = model.getDataValue('appointTime');
      if (hallScheduleId) {
        return `${date}-${hallScheduleId}`;
      }
      return `${date}`;
    });
  };
  async execute() {
    if (this.appointList.length === 0) {
      return;
    }
    let ticketPool;
    const calendarList = await getTicketDate();
    if (calendarList.length) {
      for (let i = 0; i< calendarList.length; i++) {
        const vo = calendarList[i];
        if (vo.saleStatus === 'T' && vo.parkFsyyDetailDTOS) {
          for (let j = 0; j < vo.parkFsyyDetailDTOS.length;j++) {
            const dto = vo.parkFsyyDetailDTOS[j];
            if (dto.stockNum && this.appointList.includes(`${vo.occDate}-j`)) {
              ticketPool = vo;
              ticketPool.DTO = dto;
              break;
            }
          }
        }
      }
    }

    if (ticketPool) {
      log.debug('【故宫】：有票');
      await this.createTick(ticketPool);
    }
  };

  async createTick(poolVO: any) {
    const model = await AppointTaskModel.findTask(poolVO.occDate, 2);
    if (model) {
      const touristInfo = model.getDataValue('touristInfo') as string;
      const touristList = JSON.parse(touristInfo);
      const palaceHelper = new PalaceHelper();
      let isBuy = false;
      try {
        isBuy = await palaceHelper.buy(poolVO, touristList); 
      } catch (error) {
        console.log(error)
      }
      if (isBuy) {
        log.debug('【故宫】：购票成功');
        // 更改任务状态
        const taskId = model.getDataValue('id');
        AppointTaskModel.update({ status: 0 }, taskId);
      } else {
        log.debug('【故宫】：购票失败');
      }
    }
  }
}

export default PalaceTask;